/*
 * 静态线路
 * @author      zhul
 * @createdate  2017-04-24
 */
if (typeof BusLine !== 'object') {
    var BusLine = {};
}

(function (window, undefined) {
    // 媒体区初始化
    BusLine.init = function (config) {
        var params = {
            pageSize: 7,
            pageIndex: 1,
            time: 100
        };
        this.params = $.extend({}, params, config);

        var total = linejson.length,
            ps = this.params.pageSize,
            pages;

        if (total % ps) {
            pages = parseInt(total / ps) + 1;
        } else {
            pages = parseInt(total / ps);
        }
        this.params.pages = pages;
        this.params.apidata = null;
        BusLine.params.result = {};
        BusLine.params.result.carJson = null;
        BusLine.params.result.reportJson = null;
        BusLine.params.result.enterJson = null;
        this.initWrap();
        getApiData(configjson.ip, "5003");
    };
    BusLine.pagingData = function () {
        var self = this;
        self.getLineInfo(self.linePage(self.params.pageIndex, self.params.pageSize));
        // setInterval(function () {
        //     var ps = self.params.pageSize,
        //         pages = self.params.pages;
        //     if (self.params.pageIndex >= pages) {
        //         self.params.pageIndex = 1;
        //     }
        //     console.log('分页了')
        //     self.getLineInfo(self.linePage(self.params.pageIndex, ps));
        //     setCarPos();
        //     setReportData();
        //     setEnterData();
        //     self.params.pageIndex = self.params.pageIndex + 1;
        // }, 20000);
    }

    BusLine.initWrap = function () {
        var id = this.params.lineId,
            arr = [],
            i = 1;
        while (i <= 7) {
            arr.push('<li><img src="img/banner0' + i + '.jpg"></li>');
            i++;
        }
        $('#' + id).html('<div class="line-wrap"></div><ul class="station-bg">' + arr.join('') + '</ul>');
        this.pagingData();
    }

    BusLine.getLineInfo = function (lineJson) {
        console.log('linejson', lineJson);
        var id = this.params.lineId,
            d = lineJson,
            $wraps = $('.line-wrap', '#' + id);
        if (d && d.length) {
            var item,
                $wrap = $($('#LineHtml').html()),
                sItem,
                listH,
                eachWidth,
                html = '';
            for (var i = 0, len = d.length; i < len; i++) {
                item = d[i];
                eachWidth = parseInt((938 / item.stationlist.length) * 10) / 10;
                $wrap.find('h3').text(item.lname + '路');
                var $dl = $wrap.find('dl');
                $('span', $dl)[0].innerHTML = item.ftime.substr(0,2) + ':' + item.ftime.substring(2,4);
                $('span', $dl)[1].innerHTML = item.etime.substr(0,2) + ':' + item.etime.substring(2,4);
                var index = item.ldirection.indexOf('==>');
                if(index > -1) {
                    $('em', $dl)[0].innerHTML = item.ldirection.substring(0, index - 1);
                    $('em', $dl)[1].innerHTML = item.ldirection.substring(index + 3, item.ldirection.length);
                }
                setStationW(item.stationlist, $wrap);
                html += $wrap.html();
            }
            $wraps.html(html);
        }
    }

    function setStationW(list, $wrap) {
        var sItem,
            listH = [],
            _width = parseInt((938 / list.length) * 10) / 10,
            _padding,
            carH = [],
            _left;
        if (_width > 26) {
            _padding = '0 ' + (_width - 26) / 2 + 'px';
        } else {
            _padding = '0';
        }
        for (var j = 0, jLen = list.length; j < jLen; j++) {
            _left = (parseInt(j + 1) * _width - _width / 2 - 20) + 'px';
            sItem = list[j];
            listH.push('<li  '+ (sItem.currentstation == '1' ? 'class="current"' : '' )+ ' style="width: ' + _width + 'px; padding: ' + _padding + '">' + sItem.sname + '</li>');
            carH.push('<span slno="'+sItem.slno +'" style="left: ' + _left + '"></span>')
        }
        $('.cars-pos', $wrap).html(carH.join(''));
        $('.line-info', $wrap).html(listH.join(''));
    }

    function setCarPos() {
        // if (BusLine.params.result != null && BusLine.params.result.carJson != null) {
        var d = BusLine.params.result.carJson;
        if (d && d.length) {
            var $wraps = $('.station-wrap', '#' + BusLine.params.lineId),
                $wrap,
                item,
                cItem;
            for (var i = 0, len = d.length; i < len; i++) {
                item = d[i];
                $wrap = $($wraps[i]);
                var $span = $wrap.find('.cars-pos span');
                for (var m = 0, mLen = $span.length; m < mLen; m++) {
                    var flag = false;
                    var mItem = $span[m];
                    for (var j = 0, jLen = item.buslist.length; j < jLen; j++) {
                        cItem = item.buslist[j];
                        if (cItem.slno == mItem.getAttribute('slno')) {
                            flag = true;
                            $(mItem).animate({
                                opacity: 1
                            }, 1000);
                        }
                    }
                    if(!flag){
                        $(mItem).animate({
                            opacity: 0
                        }, 900);
                    }
                }
                // $wrap.find('.cars-pos').html(carH.join(''));
            }
        }
        // }
    }
    function setCarPos2(i, $lineWraps, _width) {
        var d = BusLine.params.result.carJson;
        if (d && d[i]) {
            var _width,
                cItem,
                mItem,
                carH = [];
            for (var j = 0, jLen = d[i].buslist.length; j < jLen; j++) {
                cItem = d[i].buslist[j];
                for (var m = 0, mLen = linejson[i].stationlist.length; m < mLen; m++) {
                    mItem = linejson[i].stationlist[m];
                    if (cItem.slno == mItem.slno) {
                        var _left = (parseInt(m + 1) * _width - _width / 2 - 20) + 'px';
                        carH.push('<span style="transform:translateX('+ _left +');"></span>');
                    }
                }
            }
            $lineWraps.find('.cars-pos').html(carH.join(''));
        }
    }
    /*全局报站*/
    function setEnterData() {
        // if (BusLine.params.result != null && BusLine.params.result.enterJson != null) {
        var d = BusLine.params.result.enterJson;
        if (d) {
            $('.layer-wrap').show();
            $('.arrive-route').html(d);
        } else {
            $('.layer-wrap').hide();
        }
        // }
    }

    function setReportData() {
        var d = BusLine.params.result.reportJson;
        if (d && d.length) {
            var item,
                text,
                $wraps = $('#' + BusLine.params.lineId);
            for (var i = 0, len = d.length; i < len; i++) {
                item = d[i];

                if (item.leastNum == '-2') {
                    text = '尚未发车';
                } else if (item.leastNum == '1') {
                    text = '即将进站';
                } else {
                    text = '最近车' + item.leastNum + '站';
                }
                for (var j = 0, jLen = $('.car-no', $wraps).length; j < jLen; j++) {
                    var jItem = $('.car-no', $wraps)[j],
                        jItemName = jItem.innerHTML.substring(0, jItem.innerHTML.length - 1);
                    if (item.lname == jItemName) {
                        $('.car-tips', $wraps)[j].innerHTML = text;
                    }
                }
            }
        }
    }
    function setReportData2($wrap, name) {
        var d = BusLine.params.result.reportJson;
        if (d && d.length) {
            var text;
            for (var i = 0, len = d.length; i < len; i++) {
                var item = d[i];
                if (item.leastNum == '-2') {
                    text = '尚未发车';
                } else if (item.leastNum == '1') {
                    text = '即将进站';
                } else {
                    text = '最近车' + item.leastNum + '站';
                }
                if(name == item.lname) {
                    $('.car-tips', $wrap).html(text);
                }
            }
        }
    }
    /**
     * 获取线路翻页信息
     * pi - 当前页码
     * ps - 页大小
     */
    BusLine.linePage = function (pi, ps) {
        var result = [];

        // if (pi <= 0 || ps <= 0)
        //     return null;

        // 总记录数
        var total = linejson.length,
            pages = this.params.pages,
            end;
        if (total % ps) {
            if(pi != pages) {
                end = pi * ps;
            }else{
                end = (pi - 1) * ps + total % ps;
            }
        } else {
            end = pi * ps;
        }
        if(end > total) {
            end = total;
        }
        // 计算总页数，页数从1开始
        for (var i = ps * (pi - 1); i < end; i++) {
            result.push(linejson[i]);
        }
        return result;
    }
    /**
     * 获取视频区报站文本内容
     * @constructor
     */
    BusLine.EnterStationContent = function (cars) {
        var result = "";
        var reportJson = BusLine.ReportStationContent(cars);

        if (reportJson != null && reportJson.length > 0) {
            for (var i = 0; i < reportJson.length; i++) {
                if (reportJson[i].leastNum == "1") {
                    if (result == "") {
                        result = reportJson[i].lname.replace("路", "") + "路"
                    }
                    else {
                        result += " " + reportJson[i].lname.replace("路", "") + "路";
                    }
                }
            }

            if (result != "") {
                result += "即将进站";
            }
        }


        return result;
    }

    /**
     * 获取线路区报站文本内容
     *     {
     *       "lname": "118",
     *       "mainflag": "0",
     *       "leastNum": "-2"   //-2：尚未发车  1：即将进站   >1:还有X站
     *     },
     * @constructor
     */
    BusLine.ReportStationContent = function (cars) {
        //console.log("报站信息开始", cars);
        var result = [];
        for (var i = 0; i < linejson.length; i++) {
            for (var j = 0; j < cars.length; j++) {
                if (linejson[i].lname == cars[j].lname && linejson[i].mainflag == cars[j].mainflag) {
                    // 获取当前站的slno
                    var currentSlno = null;
                    if (linejson[i].stationlist != null && linejson[i].stationlist.length > 0) {
                        for (var m = 0; m < linejson[i].stationlist.length; m++) {
                            if (linejson[i].stationlist[m].currentstation == "1") {
                                currentSlno = linejson[i].stationlist[m].slno;
                            }
                        }
                    }

                    // 计算后的小车数
                    var buslistlen = cars[j].buslist.length;
                    var leastNum = "-2";

                    //console.log('整理后的小车数：' + buslistlen);
                    if (buslistlen > 0) {
                        if (cars[j].buslist[buslistlen - 1].slno < currentSlno - 1) {
                            leastNum = currentSlno - cars[j].buslist[buslistlen - 1].slno;//"还有" + (currentSlno - cars[j].buslist[buslistlen - 1].slno) + "站";
                        }
                        else {
                            leastNum = "1";
                        }
                    }
                    result.push({
                        "lname": linejson[i].lname,
                        "mainflag": linejson[i].mainflag,
                        "leastNum": leastNum
                    });

                    break;
                }
            }
        }

        //console.log('报站JSON', result);
        return result;

    }

    /**
     * 获取动态小车信息
     * 剔除当前站之后的动态小车
     * duration - 请求间隔时间（秒）
     * @constructor
     */
    BusLine.DynamicCar = function () {
        var carJson = null;
        if (BusLine.params.apidata != null) {
            var json = BusLine.params.apidata;
            // region << 动态小车数据整理 >>
            if (json.content != null && json.content.length > 0) {
                // 动态小车排序
                busListOrder(json.content);

                // 根据线路json和排序后的小车json比较筛选出当前站之前的小车
                for (var i = 0; i < linejson.length; i++) {
                    for (var j = 0; j < json.content.length; j++) {
                        if (json.content[j].lname == linejson[i].lname && json.content[j].mainflag == linejson[i].mainflag) {

                            // 获取当前站的slno
                            var currentSlno = null;
                            if (linejson[i].stationlist != null && linejson[i].stationlist.length > 0) {
                                for (var m = 0; m < linejson[i].stationlist.length; m++) {
                                    if (linejson[i].stationlist[m].currentstation == "1") {
                                        currentSlno = linejson[i].stationlist[m].slno;
                                    }
                                }
                            }
                            // console.log('线路：' + linejson[i].lname + ",当前站：" + currentSlno);

                            // 移除当前站之后的集合
                            if (json.content[j].buslist != null && json.content[j].buslist.length > 0) {
                                var newbuslist = [];
                                for (var k = 0; k < json.content[j].buslist.length; k++) {
                                    if (currentSlno != null && json.content[j].buslist[k].slno <= currentSlno - 1) {
                                        newbuslist.push(json.content[j].buslist[k]);
                                    }
                                }
                                json.content[j].buslist = newbuslist;
                            }
                            break;
                        }
                    }
                }

                // console.log('新小车列表：', json.content);
                carJson = json.content;

                // 设置报站信息
                var reportJson = BusLine.ReportStationContent(json.content);

                // 设置全局进站信息
                var enterJson = BusLine.EnterStationContent(json.content);
                BusLine.params.result.carJson = carJson;
                BusLine.params.result.reportJson = reportJson;
                BusLine.params.result.enterJson = enterJson;
                setCarPos();
                setReportData();
                setEnterData();
                setTimeout(function() {
                    getApiData(configjson.ip, "5003");
                }, 10000);
                console.log('动态小车', BusLine.params.result);
            }
        };
    }

    /*
     @function     JsonSort 对json排序
     @param        json     用来排序的json
     @param        key      排序的键值
     */
    function JsonSort(json, key) {
        //console.log(json);
        for (var j = 1, jl = json.length; j < jl; j++) {
            var temp = json[j],
                val = temp[key],
                i = j - 1;
            while (i >= 0 && json[i][key] > val) {
                json[i + 1] = json[i];
                i = i - 1;
            }
            json[i + 1] = temp;

        }
        //console.log(json);
        return json;
    }

    function getApiData(devid, command) {

        var devid = devid;
        var cmd = command;
        var url = "http://192.168.0.250:8081/externaldata/busdata/" + devid + "/" + cmd;
        $.ajax({
            type: "GET",
            url: url,
            dataType: 'json',
            async: true, // 设置为同步执行，否则result无法获取,true-异步，false-同步
            // timeout: 15,
            success: function (res) {
                if(res != null && res != "") {

                    result = res.content;// JSON.parse(res.content);
                    BusLine.params.apidata = result;
                    BusLine.DynamicCar();
                }
            },
            error: function (ex) {
                $('.cars-pos span').animate({
                    opacity: 0
                }, 1000);
            }
        });

    }

    function busListOrder(sourceJson) {
        for (var i = 0; i < sourceJson.length; i++) {
            if (sourceJson[i].buslist != null && sourceJson[i].buslist.length > 0) {
                JsonSort(sourceJson[i].buslist, "slno");
            }
        }
    }


})(window);







